package com.shouxin.attendance.activity;

import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.shouxin.attendance.R;
import com.shouxin.attendance.adapter.HistoryAdapter;
import com.shouxin.attendance.database.DBHelper;
import com.shouxin.attendance.database.model.SwipeCardHistory;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>刷卡历史纪录界面</p>
 * Created by Jiang on 15-10-29.
 */
public class HistoryActivity extends BaseActivity {

    private static final int PAGE_SIZE = 20;

    private RecyclerView mRecyclerView;

    private LinearLayoutManager mLayoutManager;

    private int currentPage = -1;

    private List<SwipeCardHistory> mData = new ArrayList<>();

    private boolean hasNext = false;

    private HistoryAdapter mAdapter;

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_history);
    }

    @Override
    protected void initUIViews() {
        mRecyclerView = (RecyclerView) findViewById(R.id.history_recyclerView);
    }

    @Override
    protected void initData() {
        mData.clear();
        loadHistoryByPage();
        mAdapter = new HistoryAdapter(mData, getLayoutInflater());
    }

    private void loadHistoryByPage() {
        List<SwipeCardHistory> historyList = DBHelper.getInstance().getSwipeCardHistoryDao().queryBuilder()
                .offset(++currentPage * PAGE_SIZE).limit(PAGE_SIZE).list();
        mData.addAll(historyList);
        hasNext = historyList.size() == PAGE_SIZE;
    }

    @Override
    protected void bindEvents() {
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(true);
        mRecyclerView.setItemViewCacheSize(10);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                int lastPosition = mLayoutManager.findLastVisibleItemPosition();
                if (newState == RecyclerView.SCROLL_STATE_IDLE &&
                        lastPosition == mData.size() - 1 && hasNext) {
                    loadHistoryByPage();
                    mAdapter.notifyItemRangeInserted(lastPosition, mData.size() - lastPosition - 1);
                }
            }
        });
    }
}
